import type { PayloadAction } from "@reduxjs/toolkit"
import { createSlice } from "@reduxjs/toolkit"

interface State {
	theme: "light" | "dark"
	keepAlive: boolean //是否缓存路由页面
	loading: boolean
	locale: "zh_CN" | "en_US"
	ipInfo: {
		isLock: boolean
		ip: string
		region: string
	}
	maintainInfo: {
		isLock: boolean
		info: string
	}
	timeOutInfo: {
		isLock: boolean
		msg?: string
		context?: string
	}
}

const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
const userTheme = localStorage.getItem("theme") as State["theme"]
const storeLocal = localStorage.getItem("locale") as "zh_CN" | "en_US" | undefined
const initialState: State = {
	theme: userTheme || systemTheme,
	keepAlive: true,
	loading: false,
	locale: storeLocal ?? "zh_CN",
	ipInfo: {
		isLock: false,
		ip: "",
		region: ""
	},
	maintainInfo: {
		isLock: false,
		info: ""
	},
	timeOutInfo: {
		isLock: false
	}
}
export type globalStateType = typeof initialState
const globalSlice = createSlice({
	name: "global",
	initialState,
	reducers: {
		setGlobalState(state, action: PayloadAction<Partial<State>>) {
			Object.assign(state, action.payload)
			if (action.payload.theme) {
				const body = document.body

				if (action.payload.theme === "dark") {
					if (!body.hasAttribute("theme-mode")) {
						body.setAttribute("theme-mode", "dark")
					}
				} else {
					if (body.hasAttribute("theme-mode")) {
						body.removeAttribute("theme-mode")
					}
				}
			}
		},
		setIpInfo(state, action: PayloadAction<State["ipInfo"]>) {
			Object.assign(state.ipInfo, action.payload)
		},
		setMaintainInfo(state, action: PayloadAction<State["maintainInfo"]>) {
			Object.assign(state.maintainInfo, action.payload)
		},
		setTimeOutInfo(state, action: PayloadAction<State["timeOutInfo"]>) {
			Object.assign(state.maintainInfo, action.payload)
		},
		setLoad(state, action: PayloadAction<State["loading"]>) {
			Object.assign(state, { loading: action.payload })
		}
	}
})

export const { setGlobalState, setIpInfo, setMaintainInfo, setTimeOutInfo, setLoad } = globalSlice.actions

export default globalSlice.reducer
